package com.xinyu.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Collections;

/**
 * Ensures the log directory configured for Logback exists and is writable before the app starts producing logs.
 */
@Slf4j
@Component
public class LoggingDirectoryVerifier implements InitializingBean {

    @Value("${logging.file.path:/var/log}")
    private String logDir;

    @Value("${logging.file.name:rp}")
    private String logFileName;

    @Override
    public void afterPropertiesSet() {
        Path directory = Paths.get(logDir);
        try {
            Files.createDirectories(directory);
        } catch (SecurityException | IOException e) {
            log.warn("Unable to create log directory {}: {}", directory, e.getMessage());
            return;
        }

        if (!Files.isWritable(directory)) {
            log.warn("Log directory {} is not writable. File appenders may fail to write logs.", directory);
            return;
        }

        Path probeFile = directory.resolve('.' + logFileName + "-log-check");
        try {
            Files.write(probeFile, Collections.singletonList("log-dir-check"), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            Files.deleteIfExists(probeFile);
        } catch (IOException e) {
            log.warn("Unable to write test log file {}: {}", probeFile, e.getMessage());
            return;
        }

        log.info("Log directory {} is writable; rolling file logs will be persisted.", directory);
    }
}

